'use strict'

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function searFiles() {
    let files = fs.readdirSync(__dirname);
    let blue = files.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
    });
    return blue;
}

function registerRoutes(files) {
    files.forEach(name => {
        let temFiles = path.join(__dirname, name);
        let temRoutes = require(temFiles);

        for (let ch in temRoutes) {
            let type = temRoutes[ch][0];
            let fn = temRoutes[ch][1];

            if (type === 'get') {
                router.get(ch, fn);
            } else {
                router.post(ch, fn);
            }
        }
    });
}

module.exports = function () {
    let res = searFiles();
    registerRoutes(res);
    return router.routes();
}